package com.platform.modules.phone.utils;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.utils.Md5Utils;
import com.platform.modules.phone.PhoneTopUpContants;

import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;

/**
 * 工具类
 */
public class PhoneTopUpUtils {

    /**
     * 构建  请求信息
     *
     * @param obj 订单信息
     * @return
     */
    public static final String buildRequestInfo(Object obj) throws IllegalAccessException {
        StringBuffer requestData = new StringBuffer("");

        Class clazz = obj.getClass();
        Field[] fieldList = clazz.getDeclaredFields();
        for (Field field : fieldList) {
            field.setAccessible(true);
            Object value = field.get(obj);
            // 为空不进行值拼接
            if (value != null) {
                requestData.append(value.toString());
            }
            requestData.append(PhoneTopUpContants.REQ_DATA_SPLIT_CHAR);
        }

        // 去除末尾空格
        requestData.deleteCharAt(requestData.length() - 1);
        return requestData.toString();
    }


    /**
     * 签名
     *
     * @param requestData 请求数据
     * @param key         签名K
     * @return
     */
    public static final String sign(String requestData, String key) throws IllegalAccessException {
        // 拼接K
        String signData = requestData + PhoneTopUpContants.REQ_DATA_SPLIT_CHAR + key;
        // MD5加密并转换为大写
        return Md5Utils.encryption32(signData).toUpperCase();
    }

    /**
     * 指定编码格式签名
     *
     * @param requestData 请求数据
     * @param key         签名K
     * @param charset     编码格式
     * @return
     * @throws IllegalAccessException
     */
    public static final String sign(String requestData, String key, Charset charset) throws IllegalAccessException {
        // 拼接K
        String signData = requestData + PhoneTopUpContants.REQ_DATA_SPLIT_CHAR + key;
        // MD5加密并转换为大写
        return Md5Utils.encryption32(signData, charset).toUpperCase();
    }


    /**
     * 根据响应信息  构建实体类
     *
     * @param data  响应返回的字符串
     * @param clazz 构建对象的类对象
     * @param <T>
     * @return
     */
    public static final <T> T buildObjByResponseInfo(String data, Class<T> clazz) throws ReflectiveOperationException, IOException {
        String[] dataList = data.split("\\|");
        Field[] fields = clazz.getDeclaredFields();
        JSONObject jsonObj = new JSONObject();

        // 根据分割后的字符串  给json对象赋值
        for (int i = 0; i < dataList.length; i++) {
            String value = dataList[i];
            Field field = fields[i];
            jsonObj.put(field.getName(), value);
        }
        // 转换
        return JSONObject.toJavaObject(jsonObj, clazz);
    }

}
